<?php
/**
 * 双十一主题
 */

namespace Biz\service\activity;


use Biz\cache\DoubleEleven as cDoubleEleven;
use Biz\model\activity\ActivityDoubleElevenLog as mActivityDoubleElevenLog;
use Biz\pockets\serviceTrait\_Async;
use Biz\service\activity\Coupon as sCoupon;
use Biz\service\Share as sShare;

use Doraemon\tools\Log as tLog;
use Doraemon\service\User as sUser;
use Doraemon\model\Member as mMember;
/**
 * @deprecated
 */
class DoubleEleven
{
    use _Async;

    const DEFAULT_TIMES = 2; //默认抽奖次数
    const SHARE_LIMIT_TIMES = 1; //分享限制增加抽奖次数
    const PAY_LIMIT_TIMES = 1;//支付限制增加抽奖次数
    const TIPS_MAX_LEN = 30;//中奖列表信息数量
    const LOTTERY_TYPE_COUPON = 'coupon';//优惠券
    const LOTTERY_TYPE_POINT = 'point';//积分
    const LOTTERY_TYPE_COMMODITY = 'commodity';//实物
    const LOTTERY_TYPE_AGAIN = 'again';//再来一次
    const SHARE_FINISH = 1;//分享次数使用完毕标识
    const SHARE_NOT_FINISH = 0;//分享次数未使用完毕标识

    static $play = 0;//活动场次0表示未开始/已结束
    static $activityEndTime = 0;//活动场次结束时间

    /**
     * @desc 初始化双十一活动
     */
    public static function init()
    {
        $now = time() + 0 * 86400;
        $levelOneStart = strtotime('2018-11-01');
        $levelOneEnd = strtotime('2018-11-04') - 1;
        $levelTwoStart = strtotime('2018-11-04');
        $levelTwoEnd = strtotime('2018-11-07') - 1;
        $levelThreeStart = strtotime('2018-11-07');
        $levelThreeEnd = strtotime('2018-11-10') - 1;
        $levelFourStart = strtotime('2018-11-10');
        $levelFourEnd = strtotime('2018-11-13') - 1;
        $levelFiveStart = strtotime('2018-11-13');
        $levelFiveEnd = strtotime('2018-11-16') - 1;
        if ($now >= $levelOneStart && $now <= $levelOneEnd)
        {
            self::$play = 1;
            self::$activityEndTime = $levelOneEnd;
        }
        elseif ($now >= $levelTwoStart && $now <= $levelTwoEnd)
        {
            self::$play = 2;
            self::$activityEndTime = $levelTwoEnd;
        }
        elseif ($now >= $levelThreeStart && $now <= $levelThreeEnd)
        {
            self::$play = 3;
            self::$activityEndTime = $levelThreeEnd;
        }
        elseif ($now >= $levelFourStart && $now <= $levelFourEnd)
        {
            self::$play = 4;
            self::$activityEndTime = $levelFourEnd;
        }
        elseif ($now >= $levelFiveStart && $now <= $levelFiveEnd)
        {
            self::$play = 5;
            self::$activityEndTime = $levelFiveEnd;
        }
    }

    /**
     * @desc 获取当前场次
     * @return int
     */
    public static function getPlay()
    {
        self::init();
        return self::$play;
    }

    /**
     * @desc 获取活动id
     * @return int
     */
    public static function getActivityId()
    {
        self::init();
        $index = self::$play > 0 ? self::$play : 1;
//        $list = [
//            1 => 5,
//            2 => 5,
//            3 => 5,
//            4 => 5,
//            5 => 5,
//        ];
        $list = [
            1 => 15,
            2 => 16,
            3 => 17,
            4 => 18,
            5 => 19,
        ];
        return $list[$index];
    }

    /**
     * @desc 分享信息列表
     * @return array
     */
    public static function shareInfo()
    {
        return sShare::getDoubleEleven();
    }

    /**
     * @desc 中奖列表
     * @note api调用 虚拟内容出现概率为，1条虚拟内容+4条真实内容
     * @return array
     */
    public static function tips()
    {
        self::init();
        $index = self::$play > 0 ? self::$play : 1;
        if ($index == 1) {
            $virtual = [
                '住友**o 获得北鼎桌面饮水机',
                '住友**帆 获得399减50优惠券',
                '住友**1 获得戴森卷发棒',
                '住友**江 获得10元立减券',
                '住友**喵 获得10元立减优惠券',
                '住友**仔 获得399减50优惠券',
                '住友**学 获得戴森卷发棒',
            ];
        } else if ($index == 2) {
            $virtual = [
                '住友**o 获得北鼎桌面饮水机',
                '住友**n 获得千石阿拉丁烤箱',
                '住友**帆 获得399减50优惠券',
                '住友**1 获得戴森卷发棒',
                '住友**江 获得10元立减券',
                '住友**喵 获得10元立减优惠券',
                '住友**仔 获得399减50优惠券',
                '住友**学 获得戴森卷发棒',
            ];
        } else {
            $virtual = [
                '住友**o 获得北鼎桌面饮水机',
                '住友**n 获得千石阿拉丁烤箱',
                '住友**帆 获得399减50优惠券',
                '住友**1 获得戴森卷发棒',
                '住友**江 获得10元立减券',
                '住友**h 获得拉歌蒂尼压力快锅',
                '住友**喵 获得10元立减优惠券',
                '住友**仔 获得399减50优惠券',
                '住友**学 获得戴森卷发棒',
                '住友**e 获得拉歌蒂尼压力快锅',
            ];
        }

        shuffle($virtual);
        $cache = cDoubleEleven::getTips(self::TIPS_MAX_LEN);
        $size = 4;
        $totalPage = ceil(count($cache) / $size);
        $response = [];
        $p = 0;
        while (true) {
            if ($totalPage <= $p) {
                break;
            }
            array_push($response, $virtual[$p]);
            $response = array_merge($response, array_slice($cache, $p * $size, $size));
            $p ++;
        }
        if (empty($response)) {
            array_push($response, $virtual[0]);
        }
        return $response;
    }

    /**
     * @desc 奖品列表
     * @note api调用
     * @return array
     */
    public static function lotteryList()
    {
        $response = [];
        $sort = [0,1,2,7,3,6,5,4];
        $list = self::giftList();
        foreach ($sort as $v) {
            $response[] = [
                'id' => $v,
                'name' => $list[$v]['name'],
                'path' => $list[$v]['path'],
            ];
        }
        return $response;
    }

    /**
     * @desc 奖品结构定义
     * @param string $type 类型
     * @param string $name 奖品名称
     * @param float $rate 概率
     * @param int $limit 限制数量
     * @param string $sign 标识
     * @return array
     */
    public static function giftStructure($type, $name, $rate, $limit = 0, $sign = '')
    {
        $path = '';
        $image = '';
        $id = 0;
        switch ($type) {
            case self::LOTTERY_TYPE_COMMODITY:
                if ($name == '千石阿拉丁烤箱') {
                    $path = 'http://img.hhz1.cn/Op-imageShow/84303305e05d00000phcp10?iv=1';
                    $image = 'http://img.hhz1.cn/Op-imageShow/b8b7730dw0go00000phcp13?iv=1';
                } else if ($name == '北鼎饮水机') {
                    $path = 'http://img.hhz1.cn/Op-imageShow/3f29d305d05d00000ph778t?iv=1';
                    $image = 'http://img.hhz1.cn/Op-imageShow/30fd630dw0go00000phcp13?iv=1';
                } else if ($name == '拉歌蒂尼压力快锅') {
                    $path = 'http://img.hhz1.cn/Op-imageShow/88ba7305e05d00000phcp11?iv=1';
                    $image = 'http://img.hhz1.cn/Op-imageShow/8e45e30dw0go00000phcp12?iv=1';
                } else if ($name == '戴森卷发棒') {
                    $path = 'http://img.hhz1.cn/Op-imageShow/13833305d05d00000ph778t?iv=1';
                    $image = 'http://img.hhz1.cn/Op-imageShow/13833305d05d00000ph778t?iv=1';
                }
                break;
            case self::LOTTERY_TYPE_COUPON:
                if ($name == '99减10优惠券') {
                    $path = 'http://img.hhz1.cn/Op-imageShow/3d445305e05e00000ph778r?iv=1';
                    $image = 'http://img.hhz1.cn/Op-imageShow/3971f30dw0go00000phcp11?iv=1';
                    $id = 513;//线上
//                    $id = 186;
                } elseif ($name == '159减15优惠券') {
                    $path = 'http://img.hhz1.cn/Op-imageShow/b2dd7305d05d00000ph778s?iv=1';
                    $image = 'http://img.hhz1.cn/Op-imageShow/0a78530dw0go00000phcp11?iv=1';
                    $id = 514;//线上
//                    $id = 187;
                } elseif ($name == '399减50优惠券') {
                    $path = 'http://img.hhz1.cn/Op-imageShow/bb16c305d05d00000ph778s?iv=1';
                    $image = 'http://img.hhz1.cn/Op-imageShow/624a930dw0go00000phcp12?iv=1';
                    $id = 515;//线上
//                    $id = 188;
                } elseif ($name == '10元立减优惠券') {
                    $path = 'http://img.hhz1.cn/Op-imageShow/e5e53305d05d00000ph778t?iv=1';
                    $image = 'http://img.hhz1.cn/Op-imageShow/ddf3530dw0go00000phcp11?iv=1';
                    $id = 512;//线上
//                    $id = 189;
                }
                break;
            case self::LOTTERY_TYPE_POINT:
                $path = 'http://img.hhz1.cn/Op-imageShow/c26b6305d05d00000ph778s?iv=1';
                $image = 'http://img.hhz1.cn/Op-imageShow/8e6e230dw0go00000phcp12?iv=1';
                $id = 200;
                break;
            case self::LOTTERY_TYPE_AGAIN:
                $path = 'http://img.hhz1.cn/Op-imageShow/b0315305d05d00000ph778t?iv=1';
                $image = 'http://img.hhz1.cn/Op-imageShow/c129230dw0go00000phcp13?iv=1';
                break;
        }
        return compact('type', 'name', 'path', 'image', 'rate', 'limit', 'sign', 'id');
    }

    /**
     * @desc 奖品列表
     * @return array
     */
    public static function giftList()
    {
        self::init();
        $index = self::$play > 0 ? self::$play : 1;
        $list =  [
            '1' => [
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '99减10优惠券', 15.95),
                self::giftStructure(self::LOTTERY_TYPE_POINT, '200积分', 20),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '159减15优惠券', 40),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '10元立减优惠券', 4),
                self::giftStructure(self::LOTTERY_TYPE_COMMODITY, '戴森卷发棒', 0),
                self::giftStructure(self::LOTTERY_TYPE_AGAIN, '再来一次', 10),
                self::giftStructure(self::LOTTERY_TYPE_COMMODITY, '北鼎饮水机', 0, 1, 'yinshuiji1'),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '399减50优惠券', 10),
            ],
            '2' => [
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '99减10优惠券', 15.95),
                self::giftStructure(self::LOTTERY_TYPE_COMMODITY, '戴森卷发棒', 0),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '159减15优惠券', 40),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '399减50优惠券', 10),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '10元立减优惠券', 4),
                self::giftStructure(self::LOTTERY_TYPE_COMMODITY, '千石阿拉丁烤箱', 0.05, 2, 'kaoxiang2'),
                self::giftStructure(self::LOTTERY_TYPE_AGAIN, '再来一次', 10),
                self::giftStructure(self::LOTTERY_TYPE_POINT, '200积分', 20),
            ],
            '3' => [
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '99减10优惠券', 15.95),
                self::giftStructure(self::LOTTERY_TYPE_COMMODITY, '拉歌蒂尼压力快锅', 0.05, 2, 'yaliguo3'),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '159减15优惠券', 40),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '399减50优惠券', 10),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '10元立减优惠券', 4),
                self::giftStructure(self::LOTTERY_TYPE_POINT, '200积分', 20),
                self::giftStructure(self::LOTTERY_TYPE_AGAIN, '再来一次', 10),
                self::giftStructure(self::LOTTERY_TYPE_COMMODITY, '戴森卷发棒', 0),
            ],
            '4' => [
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '99减10优惠券', 15.95),
                self::giftStructure(self::LOTTERY_TYPE_COMMODITY, '北鼎饮水机', 0.05, 0, 'yinshuiji4'),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '159减15优惠券', 40),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '399减50优惠券', 10),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '10元立减优惠券', 4),
                self::giftStructure(self::LOTTERY_TYPE_POINT, '200积分', 20),
                self::giftStructure(self::LOTTERY_TYPE_AGAIN, '再来一次', 10),
                self::giftStructure(self::LOTTERY_TYPE_COMMODITY, '戴森卷发棒', 0),
            ],
            '5' => [
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '99减10优惠券', 15.95),
                self::giftStructure(self::LOTTERY_TYPE_COMMODITY, '拉歌蒂尼压力快锅', 0.05, 2, 'yaliguo3'),
//                self::giftStructure(self::LOTTERY_TYPE_COMMODITY, '北鼎饮水机', 0.05, 1, 'yinshuiji5'),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '159减15优惠券', 40),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '399减50优惠券', 10),
                self::giftStructure(self::LOTTERY_TYPE_COUPON, '10元立减优惠券', 4),
                self::giftStructure(self::LOTTERY_TYPE_POINT, '200积分', 20),
                self::giftStructure(self::LOTTERY_TYPE_AGAIN, '再来一次', 10),
                self::giftStructure(self::LOTTERY_TYPE_COMMODITY, '戴森卷发棒', 0),
            ],
        ];
        return $list[$index];
    }

    /**
     * @desc 抽奖
     * @param int $uid 用户id
     * @param int $play 活动场次
     * @return mixed
     * @throws \Exception
     */
    public static function lottery($uid, $play)
    {
        $gift = [];
        //返回结果初始化
        $response = [
            'id' => 0,
            'type' => '',
            'times' => 0,
            'image' => '',
            'desc' => '',
            'fresh' => 0,
            'error' => 0,
            'message' => '',
        ];
        try {
            //初始化奖品列表和场次
            self::init();
            
            if (self::$play <= 0) {
                $response['type'] = 'end';
                throw new \Exception('活动未开始或者已经结束');
            }
            if ($uid <= 0) {
                $response['type'] = 'nologin';
                throw new \Exception('用户未登陆');
            }

            //获取当前用户的类型
            $user = sUser::getUser($uid);
            if ($user['type'] == mMember::AUTH_USER_BRAND) {
                $response['type'] = 'forbid';
                throw new \Exception('品牌用户不可抽奖');
            }

            //获取用户当前抽奖次数
            $lastTimes = self::getUserTimes($uid);
            if ($lastTimes <= 0) {
                if (self::shareFinish($uid) == self::SHARE_FINISH) {
                    $response['type'] = 'over';
                    $response['image'] = 'http://img.hhz1.cn/Op-imageShow/1d65830dw0go00000phcp10?iv=1';//已用完,逛商场
                } else {
                    $response['type'] = 'share';
                    $response['image'] = 'http://img.hhz1.cn/Op-imageShow/749bc30dw0go00000phcp11?iv=1';//可分享
                }
                throw new \Exception('抽奖次数已经用完');
            }

            //抽奖场次校验
            if ($play != self::$play) {
                $response['type'] = 'fresh';
                $response['fresh'] = 1;
                throw new \Exception('场次不一致');
            }

            //抽奖
            $result = self::lotteryProcess($uid);
            $result = array_values($result);
            list($isTips, $isLog, $desc, $gift, $key, $sort) = $result;

            //添加redis中奖列表
            if ($isTips){
                self::addTips($uid, $gift['name']);
            }

            //添加抽奖纪录
            if ($isLog){
                mActivityDoubleElevenLog::addData($uid, $gift['type'], $gift['name'], json_encode($gift, JSON_UNESCAPED_UNICODE), $sort);
            }

            $response = [
                'id' => $key,
                'type' => $gift['type'],
                'times' => self::getUserTimes($uid),
                'image' => $gift['image'],
                'desc' => $desc,
                'fresh' => 0,
            ] + $response;
            self::errorLog('双十一抽奖记录', [
                'uid'       => $uid,
                'isTips' => $isTips,
                'isLog' => $isLog,
                'gift' => $gift,
                'args' => func_get_args()
            ]);
        } catch (\Exception $e) {
            self::errorLog('双十一抽奖出现异常', [
                'uid'       => $uid,
                'gift' => $gift,
                'args' => func_get_args(),
                'e_file'    => $e->getFile(),
                'e_msg'     => $e->getMessage(),
                'e_line'    => $e->getLine()
            ]);
            $response = [
                'error' => 1,
                'message' => $e->getMessage()
            ] + $response;
        }
        return $response;
    }

    /**
     * @desc 抽奖
     * @param int $uid 用户id
     * @return array
     * @throws \Exception
     */
    public static function lotteryProcess($uid)
    {
        //获取奖品列表
        $giftList = self::giftList();
        $giftArray = [];
        foreach ($giftList as $key => $value)
        {
            $isNotFill = false;
            if($value['type'] == self::LOTTERY_TYPE_COMMODITY) {
                $isNotFill = cDoubleEleven::getCommodity($value['sign']) >= $value['limit'];
            }
            if (!$isNotFill) {
                $item = array_fill(0, $value['rate'] * 20, $key);
                $giftArray = array_merge($giftArray, $item);
            }
        }

        $times = 300;
        while (true) {
            if ($times < 0) {
                throw new \Exception('系统繁忙,请稍后再试');
            }
            $times --;
            //随机选择奖励
            $randKey = array_rand($giftArray);
            $key = $giftArray[$randKey];
            $gift = $giftList[$key];

            //扣减抽奖次数
            $lastTimes = cDoubleEleven::decrUserTimes($uid);
            if ($lastTimes < 0) {
                throw new \Exception('抽奖次数已经用完');
            }
            //发放奖品
            $isTips = false;
            $isLog = false;
            $desc = '';
            $sort = 0;
            switch ($gift['type']) {
                case self::LOTTERY_TYPE_AGAIN:
                    cDoubleEleven::incrUserTimes($uid);
                    break;
                case self::LOTTERY_TYPE_COMMODITY:
                    //todo 发放奖品
                    $limit = $gift['limit'];
                    try {
                        cDoubleEleven::setCommodityLimit($gift['sign'], $limit);
                    } catch (\Exception $e) {
                        if ($e->getCode() == cDoubleEleven::CODE_LIMIT) {
                            cDoubleEleven::incrUserTimes($uid);
                            continue;
                        }
                        throw $e;
                    }
                    $isTips = true;
                    $isLog = true;
                    $desc = '恭喜获得「'.$gift['name'].'」，请前往「我的-帮助与反馈-右上角已经反馈按钮」中填写你的姓名、电话、收货地址，我们将在双11活动结束后的7个工作日内将奖品统一发出，请耐心等待哦。';
                    $sort = 1;
                    break;
                case self::LOTTERY_TYPE_POINT:
                    //todo 添加积分
                    $isTips = true;
                    $isLog = true;
                    $desc = '恭喜获得「'. $gift['name'] .'」，积分（优惠券）已经发送到你的账户中，购买商品就可以直接使用哦。';
                    self::addPoint($uid, $point = $gift['id']);
                    break;
                case self::LOTTERY_TYPE_COUPON:
                    //todo 发放优惠券
                    $isTips = true;
                    $isLog = true;
                    $desc = '恭喜获得「'. $gift['name'] .'」，积分（优惠券）已经发送到你的账户中，购买商品就可以直接使用哦。';
                    self::addCoupon($uid, $couponId = $gift['id']);
                    break;
                default:
                    throw new \Exception('未知类型');
                    break;
            }
            break;
        }
        return compact('isTips','isLog', 'desc', 'gift', 'key', 'sort');
    }

    /**
     * @desc 发放优惠券
     * @param int $uid 用户id
     * @param int $couponId 优惠券id
     * @throws \Exception
     */
    public static function addCoupon($uid, $couponId)
    {
        self::_async($uid, $couponId);
    }
    /**
     * @desc 异步发放优惠券
     * @param int $uid 用户id
     * @param int $couponId 优惠券id
     * @throws \Exception
     */

    public static function _async_addCoupon($uid, $couponId)
    {
        sCoupon::sendToUser($couponId, $uid, '双十一抽奖活动');
    }

    /**
     * @desc 添加积分
     * @param int $uid 用户id
     * @param int $point 积分数量
     * @throws \Exception
     */
    public static function addPoint($uid, $point)
    {
        self::_async($uid, $point);
    }

    /**
     * @desc 异步添加积分
     * @param int $uid 用户id
     * @param int $point 积分数量
     * @throws \Exception
     */
    public static function _async_addPoint($uid, $point)
    {
        $source = 'admin';
        $event_name=\Doraemon\tools\PointConfig::POINT_TYPE_ADM_AWARD;
        $request_id = $source.$event_name.$uid.date('YmdHis');
        $ext_info='抽奖活动';
        \Hhzbeads\Point\PointClient::awardPoint($uid, $point,$event_name , $request_id, $source, $ext_info);
    }

    /**
     * @desc 添加redis中奖纪录
     * @param int $uid 用户id
     * @param string $giftName 中奖名称
     * @return mixed
     * @throws \Exception
     */
    public static function addTips($uid, $giftName)
    {
        $user = sUser::getUserInfo($uid);
        $nick = mb_substr($user['nick'], -1);
        $desc = sprintf("住友**%s 获得%s", $nick, $giftName);
        cDoubleEleven::setTips($desc, self::TIPS_MAX_LEN);
    }

    /**
     * @desc 分享次数是否已经使用完全
     * @param int $uid 用户id
     * @return mixed
     */
    public static function shareFinish($uid)
    {
        $type = cDoubleEleven::KEY_TYPE_SHARE;
        $shareTimes = cDoubleEleven::getUserData($uid, $type);
        return $shareTimes >= self::SHARE_LIMIT_TIMES ? self::SHARE_FINISH : self::SHARE_NOT_FINISH;
    }

    /**
     * @desc 分享获取抽奖次数
     * @param int $uid 用户id
     * @return mixed
     * @throws \Exception
     */
    public static function share($uid)
    {
        if ($uid <= 0) {
            //未登录
            $times = self::DEFAULT_TIMES;
            $finish = self::SHARE_NOT_FINISH;
        } else {
            $type = cDoubleEleven::KEY_TYPE_SHARE;
            $finish = self::SHARE_NOT_FINISH;
            $times = self::getUserTimes($uid);
            cDoubleEleven::initLimitTimes($uid, $type);
            try {
                $shareTimes = cDoubleEleven::getUserData($uid, $type);
                //分享次数限制
                if ($shareTimes >= self::SHARE_LIMIT_TIMES) {
                    throw new \Exception('分享奖励次数已经用完');
                }

                //添加分享次数
                $shareTimes = cDoubleEleven::incrUserTimes($uid, $type);
                //分享次数限制
                if ($shareTimes > self::SHARE_LIMIT_TIMES) {
                    throw new \Exception('分享奖励次数已经用完');
                }

                //增加抽奖次数
                $times = cDoubleEleven::incrUserTimes($uid);

                //分享次数限制,最后一次判断提示
                if ($shareTimes == self::SHARE_LIMIT_TIMES) {
                    throw new \Exception('分享奖励次数已经用完');
                }
            } catch (\Exception $e) {
                $finish = self::SHARE_FINISH;
            }
        }
        $response = [
            'times' => $times,
            'finish' => $finish
        ];

        self::errorLog('双十一分享获取抽奖次数记录', [
            'uid'       => $uid,
            'response' => $response,
            'args' => func_get_args()
        ]);
        return $response;
    }

    /**
     * @desc 支付获取抽奖次数
     * @param int $uid 用户id
     * @return mixed
     */
    public static function pay($uid)
    {
        $message = '';
        try {
            self::init();
            if (self::$play == 0 || $uid <= 0)
            {
                throw new \Exception('活动未开始或者已结束');
            }

            $type = cDoubleEleven::KEY_TYPE_PAY;
            self::getUserTimes($uid);
            cDoubleEleven::initLimitTimes($uid, $type);

            $payTimes = cDoubleEleven::getUserData($uid, $type);
            //支付获取次数限制
            if ($payTimes >= self::PAY_LIMIT_TIMES) {
                throw new \Exception('支付奖励次数已经用完');
            }

            $times = cDoubleEleven::incrUserTimes($uid, $type);
            //分享次数限制
            if ($times > self::PAY_LIMIT_TIMES) {
                throw new \Exception('支付奖励次数已经用完');
            }

            //增加抽奖次数
            cDoubleEleven::incrUserTimes($uid);
        } catch (\Exception $e) {
            //todo error log
            $message = $e->getMessage();
        }
        self::errorLog('双十一支付获取抽奖次数记录', [
            'uid'       => $uid,
            'play'       => self::$play,
            'message' => $message,
            'args' => func_get_args()
        ]);
    }

    /**
     * @desc 获取抽奖次数
     * @param int $uid 用户id
     * @return int
     * @throws \Exception
     */
    public static function getUserTimes($uid)
    {
        return $uid > 0 ? intval(cDoubleEleven::getUserTimes($uid, self::DEFAULT_TIMES)) : self::DEFAULT_TIMES;
    }

    /**
     * @desc 错误日志
     * @param string $title 日志名称
     * @param array $params 存储参数
     * @return mixed
     */
    public static function errorLog($title, array $params)
    {
        tLog::general_lottery_warning($title, $params);
    }

    /**
     * @desc 抽奖用户
     * @return mixed
     */
    public static function groupUser()
    {
        $list = mActivityDoubleElevenLog::groupUser();
        return $list;
    }

    /**
     * @desc 抽奖列表
     * @param int $page 页码
     * @return mixed
     */
    public static function getLog($page, $size)
    {
        $offset = ($page - 1) * $size;
        $offset = $offset > 0 ? $offset : 0;
        $count = mActivityDoubleElevenLog::getCount();
        $list = mActivityDoubleElevenLog::getList($offset, $size);
        return compact('count', 'list');
    }

    public static function getTtl($uid)
    {
        $timesKey = cDoubleEleven::getKey($uid, cDoubleEleven::KEY_TYPE_TIMES);
        $shareKey = cDoubleEleven::getKey($uid, cDoubleEleven::KEY_TYPE_SHARE);
        $payKey = cDoubleEleven::getKey($uid, cDoubleEleven::KEY_TYPE_PAY);
        return [
            'times' => ' ttl:'. cDoubleEleven::ttl($timesKey). ' value:'. cDoubleEleven::get($timesKey),
            'share' => ' ttl:'. cDoubleEleven::ttl($shareKey). ' value:'. cDoubleEleven::get($shareKey),
            'pay' => ' ttl:'. cDoubleEleven::ttl($payKey). ' value:'. cDoubleEleven::get($payKey),
        ];
    }

    public static function clearAll($isDel = false)
    {
        $rs =  cDoubleEleven::keys(cDoubleEleven::_CACHE_KEY_PREFIX_ . '*');
        if ($rs) {
            foreach ($rs as $v) {
                echo $v . ' ttl:'. cDoubleEleven::ttl($v) . PHP_EOL;
                if (strpos($v, cDoubleEleven::KEY_TYPE_TIMES)) {
                    echo $v . ' value:'. cDoubleEleven::get($v) . PHP_EOL;
                }
                if (strpos($v, cDoubleEleven::KEY_TYPE_SHARE)) {
                    echo $v . ' value:'. cDoubleEleven::get($v) . PHP_EOL;
                }
                if (strpos($v, cDoubleEleven::KEY_TYPE_PAY)) {
                    echo $v . ' value:'. cDoubleEleven::get($v) . PHP_EOL;
                }
                if ($isDel) {
                    cDoubleEleven::del($v);
                }
            }
        }
    }

}